package com.jianying.day08;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink01_KeyedState_ValueState_1
 * Package: com.atguigu.day08
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/9 09:40
 * @Version: 1.0
 */
public class Flink05_KeyedState_ReduceState {
    public static void main(String[] args) throws Exception {
        // TODO 统计每种传感器，水位和
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> mapDS = env.socketTextStream("localhost", 8888)
                .map(new WaterSensorMapFunction());

        // TODO 按键分组 ID
        KeyedStream<WaterSensor, String> keyByDS = mapDS.keyBy(WaterSensor::getId);

        // TODO 分组后数据处理
       keyByDS.process(
               new KeyedProcessFunction<String, WaterSensor, String>() {
                   ReducingState<Integer> vcSumReduceState;

                   @Override
                   public void open(Configuration parameters) throws Exception {
                       ReducingStateDescriptor<Integer> reducingStateDescriptor =
                               new ReducingStateDescriptor<Integer>("vcSumReduceState", new ReduceFunction<Integer>() {
                                   @Override
                                   public Integer reduce(Integer t1, Integer t2) throws Exception {
                                       return t1 + t2;
                                   }
                               }, Integer.class);
                       vcSumReduceState =  getRuntimeContext().getReducingState(reducingStateDescriptor);
                   }

                   @Override
                   public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                       Integer vc = value.getVc();
                       vcSumReduceState.add(vc);
                       Integer vcSum = vcSumReduceState.get();
                       out.collect("传感器：" + ctx.getCurrentKey() + ",水位值累加结果:" + vcSum);
                   }
               }
       ).printToErr();

        env.execute();
    }
}
